<template>
	<view class="search-container">
		<!-- 顶部区域 -->
		<searchBox v-model="query" @confirm="addHistory" @cancel="cancel"></searchBox>
		<!-- 底部区域 -->
		<view class="history-box">
			<view class="top">
				<text>历史搜索</text>
				<icon @tap="clear" type="clear"></icon>
			</view>
			<view class="bottom">
				<view v-for="(item, index) in history" :key="index" @tap="clickHistory(item)">{{ item }}</view>
			</view>
		</view>
	</view>
</template>

<script>
	import searchBox from '../../components/searchBox.vue';
	// 导入key
	import {
		KEY
	} from '../../utils/keys.js';
	export default {
		components: {
			searchBox
		},
		data() {
			return {
				// 双向绑定的内容
				query: '',
				// 搜索历史
				history: []
			};
		},
		onShow() {
			// 清空内容
			this.query = '';
			const history = uni.getStorageSync(KEY);
			// console.log('history:',history)
			// 短路运算,
			// 第一个为true 直接用,第一个为false 用 ||之后
			this.history = history || [];
		},
		methods: {
			// 点击历史
			clickHistory(item) {
				this.query = item;
				// 跳转搜索结果页
				uni.navigateTo({
					url: `../searchResult/searchResult?query=${this.query}`
				});
			},
			// 清空历史
			clear() {
				this.history = [];
				// 删除历史
				uni.clearStorageSync(KEY);
			},
			// 添加搜索历史
			addHistory() {
				if (this.query === '') {
					return;
				}
				// 到这里说明有值
				this.history.push(this.query);
				// 去重
				const set = new Set(this.history);
				this.history = [...set];
				// 判断长度
				if (this.history.length > 5) {
					// 超出长度 删除第一个
					this.history.shift();
				}
				// 更新缓存
				uni.setStorageSync(KEY, this.history);
				// 跳转搜索结果页
				uni.navigateTo({
					url: `../searchResult/searchResult?query=${this.query}`
				});
			},
			cancel() {
				this.query = '';
			}
		}
	};
</script>

<style lang="less">
	.search-container {
		.history-box {
			padding: 25rpx 30rpx 0 20rpx;

			.top {
				display: flex;
				justify-content: space-between;
				align-items: center;
			}

			.bottom {
				display: flex;
				flex-wrap: wrap;
				margin-top: 30rpx;

				view {
					padding: 20rpx;
					margin-right: 30rpx;
					margin-bottom: 20rpx;
					background-color: #dddddd;
				}
			}
		}
	}
</style>
